import "./reset.css";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import ReCropperPreview from "@/components/ReCropperPreview";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import {
  cloneDeep,
  deviceDetection,
  getKeyList,
  hideTextAtIndex,
  isAllEmpty
} from "@pureadmin/utils";
import { ElMessageBox, ElProgress } from "element-plus";
import {
  computed,
  h,
  onMounted,
  reactive,
  ref,
  type Ref,
  toRaw,
  watch
} from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧部门树的id
    deptId: "",
    username: "",
    phone: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "Id",
      width: 90
    },
    {
      label: "用户名称",
      prop: "UserName",
      minWidth: 130
    },
    {
      label: "用户昵称",
      prop: "NickName",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "Sex",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={row.Sex === 1 ? "danger" : null}
          effect="plain"
        >
          {row.Sex === 2 ? "女" : "男"}
        </el-tag>
      )
    },
    {
      label: "部门",
      prop: "DeptName",
      minWidth: 90
    },
    {
      label: "手机号码",
      prop: "Phone",
      minWidth: 90,
      formatter: ({ Phone }) => hideTextAtIndex(Phone, { start: 3, end: 6 })
    },
    {
      label: "状态",
      prop: "Status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.Status}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "编辑时间",
      minWidth: 90,
      prop: "UpdatedAt"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        !row.Status ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.UserName
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        http
          .post(changeHttpLink("/api/System/change_user_status"), {
            data: {
              listIds: [row.Id],
              status: row.Status
            }
          })
          .then((res: any) => {
            if (res.Success) {
              message(`已${!row.Status ? "停用" : "启用"}${row.UserName}`, {
                type: "success"
              });
              onSearch();
            } else {
              !row.Status ? (row.status = true) : (row.status = false);
              message(res.Message, { type: "error" });
            }
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
            loading.value = false;
          })
          .catch(err => {
            !row.Status ? (row.status = true) : (row.status = false);
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        !row.Status ? (row.status = true) : (row.status = false);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    handleRemoveUser([row.UserName]).then(res => {
      if (res) {
        message(`您删除了用户编号为${row.Id}的这条数据`, { type: "success" });
        onSearch();
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listUserName = curSelected.map(item => {
      return item.Id;
    });
    handleRemoveUser(listUserName).then(res => {
      if (res) {
        message(`已删除用户编号为【 ${getKeyList(curSelected, "Id")}】的数据`, {
          type: "success"
        });
        tableRef.value.getTableRef().clearSelection();
        onSearch();
      }
    });
  }

  function handleRemoveUser(listUserName) {
    return new Promise(resolve => {
      const params = {
        listIds: listUserName
      };
      loading.value = true;
      http
        .post(changeHttpLink("/api/System/user_remove"), {
          data: params
        })
        .then((res: any) => {
          loading.value = false;
          if (res.Success) {
            resolve(true);
          } else {
            message(res.Message, { type: "error" });
            resolve(false);
          }
        })
        .catch(err => {
          loading.value = false;
          message(err.message, { type: "error" });
          resolve(false);
        });
    });
  }

  async function onSearch() {
    // syncmenu()
    loading.value = true;
    const searchLimit = toRaw(form);
    const paginationInfo = toRaw(pagination);
    loading.value = true;
    const params: any = {
      UserName: searchLimit.username ?? "",
      DeptId:
        searchLimit.deptId.toString().length > 0
          ? parseInt(searchLimit.deptId)
          : 0,
      Status: !isAllEmpty(form.status) ? form.status : -1,
      Phone: searchLimit.phone ?? "",
      PageIndex: paginationInfo.currentPage,
      PageSize: paginationInfo.pageSize
    };
    http
      .post(changeHttpLink("/api/System/user_list"), { data: params })
      .then((res: any) => {
        if (res.Data != null) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        }
        setTimeout(() => {
          loading.value = false;
        }, 300);
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.deptId = "";
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ Id, selected }) {
    form.deptId = selected ? Id : "";
    onSearch();
  }

  function formatHigherDeptOptions(treeList) {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = !treeList[i].Status;
      formatHigherDeptOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  function openDialog(title = "新增", row: any) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          title,
          higherDeptOptions: formatHigherDeptOptions(higherDeptOptions.value),
          dept_id: row?.DeptId ?? 0,
          nickname: row?.NickName ?? "",
          username: row?.UserName ?? "",
          password: row?.Password ?? "",
          phone: row?.Phone ?? "",
          email: row?.Email ?? "",
          sex: row?.Sex ?? 1,
          status: row?.Status == true ? 1 : 0,
          remark: row?.Remark ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了登录账号为【${curData.username}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Id: 0,
              NickName: curData?.nickname ?? "",
              UserName: curData?.username ?? "",
              Password: curData?.password ?? "",
              Phone: curData?.phone ?? "",
              Email: curData?.email ?? "",
              Sex: curData?.sex ?? 1,
              DeptId: curData?.dept_id ?? 0,
              Remark: curData?.remark ?? "",
              Status: curData.status == 1
            };
            if (title !== "新增") {
              formData.Id = curData.id;
            }
            http
              .post(changeHttpLink("/api/System/user_edit"), {
                data: formData
              })
              .then((res: any) => {
                if (res.Success) {
                  chores();
                } else {
                  message(res.Message, { type: "error" });
                }
                loading.value = false;
              })
              .catch(err => {
                loading.value = false;
                message(err.message, { type: "error" });
              });
          }
        });
      }
    });
  }

  const cropRef = ref();

  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(ReCropperPreview, {
          ref: cropRef,
          imgSrc: row.Avatar || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: done => {
        console.log("裁剪后的图片信息：", avatarInfo.value);
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.UserName} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <el-form ref={ruleFormRef} model={pwdForm}>
            <el-form-item
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <el-input
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </el-form-item>
          </el-form>
          <div class="my-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(valid => {
          if (valid) {
            loading.value = true;
            const params = {
              username: row.UserName,
              pwd: pwdForm.newPwd
            };
            http
              .post(changeHttpLink("/api/System/change_user_pwd"), {
                data: params
              })
              .then((res: any) => {
                if (res.Success) {
                  message(`已成功重置 ${row.UserName} 用户的密码`, {
                    type: "success"
                  });
                  done(); // 关闭弹框
                  onSearch(); // 刷新表格数据
                } else {
                  message(res.Message, { type: "error" });
                }
                loading.value = false;
              })
              .catch(err => {
                loading.value = false;
                message(err.message, { type: "error" });
              });
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    let roleId = row?.RoleId ?? "";
    if (roleId == 0) {
      roleId = "";
    }
    addDialog({
      title: `分配 ${row.username} 用户的角色`,
      props: {
        formInline: {
          username: row?.UserName ?? "",
          nickname: row?.NickName ?? "",
          roleOptions: roleOptions.value ?? [],
          roleId
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        loading.value = true;
        const params = {
          userId: row.Id,
          roleId: curData.roleId
        };
        http
          .post(changeHttpLink("/api/System/change_user_role"), {
            data: params
          })
          .then((res: any) => {
            if (res.Success) {
              done();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
            loading.value = false;
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      }
    });
  }

  onMounted(async () => {
    treeLoading.value = true;
    await onSearch();
    getDeptList();
    getAllRoleList();
  });

  // function syncmenu() {
  //   loading.value = true;
  //   http
  //     .post(changeHttpLink("/api/System/old_menu"))
  //     .then((res: any) => {
  //       loading.value = false;
  //     })
  //     .catch(err => {
  //       loading.value = false;
  //       message(err.message, { type: "error" });
  //     });
  // }

  //角色列表
  function getAllRoleList() {
    loading.value = true;
    http
      .get(changeHttpLink("/api/System/role_select"))
      .then((res: any) => {
        if (res.Data != null) {
          roleOptions.value = res.Data;
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  //部门数据
  function getDeptList() {
    const params = {
      name: "",
      status: -1
    };
    http
      .post(changeHttpLink("/api/System/dept_list"), { data: params })
      .then((res: any) => {
        if (res.Data != null) {
          const newData = res.Data;
          treeData.value = handleTree(newData, "Id", "ParentId");
          higherDeptOptions.value = cloneDeep(treeData.value);
        }
        treeLoading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
